#! /usr/bin/env python
#coding=utf-8

import base_object
import math
import t_const,t_cmd
import random,copy

class CEvent(object):
	def __init__(self):
		self.time = 0
		self.event = None
		pass

class CMapEvent(base_object.CObject):
	def __init__(self, mapmgr):
		self.sizelist = {}
		self.timelist = {}
		# 触发事件列表
		self.on_eventlist = {}
		self.entsum = 0
		self.mapmgr = mapmgr
		pass

	def destroy(self):
		pass

	# 加载相应地图的事件列表
	def loadmapevent(self, map_name, dicPlayersuid):
		self.dicPlayersuid = dicPlayersuid
		self.eventlist = {}
		self.entsum = 0
		maps = __import__("tgame_map_%s_event"%map_name)
		for eventname in maps.data:
			self.addevent(maps.data[eventname], eventname)
		pass

	def addevent(self, event, eventname):
		ent = CEvent()
		if event["type"] == "Warning":
			ent.event = event
			self.sizelist[eventname] = ent

		self.entsum += 1
		pass

	# 更新当前已经触发的事件
	def event_update(self):
		copy_array = copy.copy(self.on_eventlist)
		for entn in copy_array:
			event = copy_array[entn]
			if event.event["type"] == "Warning":
				# 出现僵尸
				# 得到出现位置
				pos = event.event["zbpos"]
				# 出现范围
				size = event.event["zbsize"]
				# 根据范围生成随机坐标
				x = random.randint(size[0]/2-size[0], size[0]/2)
				y = random.randint(size[1]/2-size[1], size[1]/2)
				pos = (pos[0] + x,pos[1] + y)
				param = (pos[0], pos[1])
				# 向所有玩家广播,param位置出现僵尸
				self.send_event( t_cmd.S_GAME_BULZB, param)

			#每帧增加相应的时间 毫秒
			event.time += 1000 / t_const.FPS_SERVER
			#如果到达时间 则事件停止 释放
			if event.time >= event.event["time"]:
				del self.on_eventlist[entn]
				print "event ovent!!!!!!!!!!!!!!!!!"
		pass

	def update(self):
		copy_array = copy.copy(self.sizelist)
		for entn in copy_array:
			ent = copy_array[entn]
			if not ent:
				continue
			# 判断所有玩家坐标是否达到事件点范围
			for uid in self.dicPlayersuid:
				pos = self.dicPlayersuid[uid].pos
				x = math.fabs(ent.event["pos"][0]-pos[0])
				y = math.fabs(ent.event["pos"][1]-pos[1])
				length = math.sqrt(x*x + y*y)
				if length <= ent.event["size"]:
					# 通知所有玩家,事件被触发
					param = (uid, entn)
					self.send_event( t_cmd.S_GAME_EVENT, param)
					# 删除事件
					self.sizelist[entn] = None
					del self.sizelist[entn]
					# 添加事件至已触发事件中
					self.on_eventlist[entn] = ent

		self.event_update()

	def send_event(self, event, param):
		self.mapmgr.send_game_event( event, param)